package com.black.cat.jvm.rtda;

import com.black.cat.jvm.classfile.ByteUtil;

/**
 * @Author blackcat
 * @create 2021/8/12 15:33
 * @version: 1.0
 * @description:操作数栈
 */
public class OperandStack {

    private int size = 0;
    private Slot[] operands;


    public OperandStack(int size) {
        operands = new Slot[size];
        for (int i = 0; i < size; i++) {
            operands[i] = new Slot();
        }
    }

    public void pushInt(int val) {
        operands[size].num = val;
        size++;
    }

    public int popInt() {
        size--;
        return operands[size].num;
    }

    public void pushRef(Object val) {
        operands[size].ref = val;
        size++;
    }

    public Object popRef() {
        size--;
        Object val = operands[size].ref;
        operands[size].ref = null;
        return val;
    }


    public void pushFloat(float val) {
        operands[size].num = Float.floatToIntBits(val);
        size++;
    }

    public Float popFloat() {
        --size;
        return Float.intBitsToFloat(operands[size].num);
    }

    public void pushLong(long val) {
        int[] ints = ByteUtil.long2IntArr(val);
        operands[size++].num = ints[0];
        operands[size++].num = ints[1];
    }

    public long popLong() {
        size--;
        size--;
        return ByteUtil.int2Long(operands[size].num, operands[size + 1].num);
    }

    public void pushDouble(double val) {
        long res = Double.doubleToLongBits(val);
        pushLong(res);
    }

    public double popDouble() {
        long res = popLong();
        return Double.longBitsToDouble(res);
    }

}
